import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { withRouter } from 'react-router';
import fetch from 'API/fetch';
import Loading from '@kuiper-components/loading';
import moment from 'moment'
import { SSL_CATEGORY_KEY_LABEL_MAP } from '../../../../../common/constants';
import { datetime } from '../../../../../common/formatter';
import Label from '../../../../components/Label';
import RaskSelect from '../../../../components/RaskSelect';
import CategoryStat from './CategoryStat';
import WarningDetail from './WarningDetail';
import s from './style.module.css';

function warningStatsBuilder(warning = {}) {
	let text;
	if (warning.ignoredTime) {
		text = '已忽略';
	} else if (warning.isResolved) {
		text = '已修复';
	} else {
		text = '待修复';
	}
	return text;
}

const aviliablDateRange = date => {
	if (date) {
		const res = {};
		if (date[0] && date[0] !== '') {
			res.startTime = date[0];
		}
		if (date[1]) {
			res.endTime = date[1];
		}

		return JSON.stringify(res) !== '{}' ? res : undefined;
	}
	return date;
};
function DetailChart({
	className,
	jobId,
	detectTime,
	protocol,
	result,
	prevResult,
	getDropdownRef,
}) {
	const [dateRask, setDateRask] = React.useState({ detectTime: 'last', detectType: 'last' });
	const [loading, setLoading] = React.useState(false)
	const [data, setData] = React.useState([])
	const getResultData = (range = 'last', startTime, endTime) => {
		if (!jobId) {
			return false;
		}
		setLoading(true)
		let r = range
		let st = startTime
		let et = endTime
		if (dateRask?.dateRange) {
			r = dateRask?.detectTime
			st = dateRask?.dateRange[0]
			et = dateRask?.dateRange[1]
		}
		let url = `/api/v2/repodatas/report-task?jobId=${jobId}&taskType=ssl&range=${r}`;
		if (r === 'range') {
			url += `&startTime=${new Date(moment(st).format('YYYY-MM-DD HH:mm:ss')).toISOString()}
			&endTime=${new Date(moment(et).format('YYYY-MM-DD HH:mm:ss')).toISOString()}`;
		} else {
			url += `&limit=10`;
		}
		fetch(url, {
			method: 'GET',
		}).then(res => {
			// if (range === 'range') {
			// 	this.init(res.TaskData);
			// } else {
			// 	this.init(res.TaskData[0] ? [res.TaskData[0]] : []);
			// }
			// const restt = resultNumbers(res.TaskData);
			// const resultNumbers_ = restt || [];
			// this.setState({
			// 	allData: res.TaskData,
			// 	resultNumbers: resultNumbers_,
			// 	loading: false,
			// 	vulRes: restt,
			// });
			setData(res)
		});
	};

	const handleDateRask = val => {
		const dateRange = val?.dateRange;
		setDateRask({
			dateRange,
			detectType: val?.detectType,
			detectTime: dateRange.length === 2 ? val?.detectTime : 'last'
		});
	};
	React.useEffect(() => {
		getResultData()
	}, [dateRask])
	const { warningsData, titleList } = React.useMemo(() => {
		let initTasks = data?.TaskData || [];
		// if (!dateRask?.detectTime) {
		// 	initTasks = data?.TaskData || [];
		// } else {
		// 	initTasks = dateRask?.detectTime === 'last' ? [result] : [prevResult];
		// }
		const titleList = [];
		const warningsData = initTasks.reduce(
			(obj, task) => {
				const warnings = task?.result?.warnings || [];
				warnings.forEach(w => {
					titleList.push(w?.title);
					const cate = w?.category;
					if (obj[cate]) {
						obj[cate].push({
							...w,
							datetime: task?.endTime,
							status: warningStatsBuilder(w),
						});
					}
				});
				return obj;
			},
			Object.keys(SSL_CATEGORY_KEY_LABEL_MAP).reduce((obj, s) => {
				obj[s] = [];
				return obj;
			}, {})
		);

		return {
			warningsData,
			titleList: [...new Set(titleList)],
		};
	}, [data]);
	let date = '';
	return (
		<div className={cn(className, s.detailChart)}>
			<div className={s.head}>
				<div className={s.title}>
					<Label className={s.label}>SSL安全</Label>
					{dateRask.detectTime && (
						<div className={s.detectTime}>
							<div className={s.date}>{datetime(date)}</div>
						</div>
					)}
					{protocol === 'http:' && (
						<div className={s.protocol}>
							<svg
								width="16"
								height="16"
								viewBox="0 0 16 16"
								fill="none"
								xmlns="http://www.w3.org/2000/svg"
							>
								<rect opacity="0.01" width="16" height="16" fill="#F04038" />
								<path
									fillRule="evenodd"
									clipRule="evenodd"
									d="M2.32 2.32C3.84 0.8 5.84 0 8 0C12.48 0 16 3.6 16 8.08C16 12.48 12.4 16 7.92 16C3.52 16 0 12.4 0 7.92C0 5.84 0.88 3.84 2.32 2.32ZM1.04 7.92C0.96 11.84 4.08 14.96 8 14.96C11.92 14.96 14.96 11.92 14.96 8C14.96 4.16 11.84 1.04 8 1.04C4.16 0.96 1.04 4.08 1.04 7.92ZM7.2 9.2C7.2 9.76 7.52 9.92 8.08 9.92C8.64 9.92 8.64 9.6 8.64 9.2C8.68 8.44 8.7 7.67999 8.72 6.91999C8.74 6.15999 8.76 5.4 8.8 4.64C8.88 4.08 8.8 3.68 8 3.68C7.2 3.68 7.12 4 7.12 4.64L7.2 6.64V9.2ZM8 12.88C8.56 12.88 8.96 12.56 9.04 11.92C8.88 11.36 8.56 10.96 7.92 11.04C7.28 11.04 6.88 11.36 6.96 12C7.04 12.56 7.44 12.88 8 12.88Z"
									fill="#F04038"
								/>
							</svg>
							<p className={s.text}>
								该站点为HTTP站点，仅HTTPS站点可使用SSL安全监测。
							</p>
						</div>
					)}
				</div>
				<RaskSelect
					className={s.selectContainer}
					value={dateRask}
					onChange={handleDateRask}
					resultLength={data?.TaskCount || 0}
				/>
			</div>
			<CategoryStat
				key="protocol"
				className={s.category}
				category="protocol"
				data={warningsData}
				pieTitle="SSL漏洞分布"
				tableTitle="SSL漏洞TOP 10"
				title="SSL漏洞"
			/>
			<CategoryStat
				key="certificate"
				className={s.category}
				category="certificate"
				data={warningsData}
				pieTitle="SSL证书配置分布"
				tableTitle="SSL证书配置统计"
				title="SSL证书配置"
			/>
			<WarningDetail
				getDropdownRef={getDropdownRef}
				data={warningsData}
				titleList={titleList}
			/>
		</div>
	);
}

DetailChart.propTypes = {
	className: PropTypes.string,
	match: PropTypes.shape({
		params: PropTypes.shape({
			jobId: PropTypes.string,
		}),
	}),
	detectTime: PropTypes.string,
	protocol: PropTypes.string.isRequired,
	result: PropTypes.shape({
		endTime: PropTypes.object,
	}),
	prevResult: PropTypes.shape({
		endTime: PropTypes.object,
	}),
	taskType: PropTypes.string,
	getDropdownRef: PropTypes.func,
};

DetailChart.defaultProps = {
	className: '',
};

export default withRouter(DetailChart);
